package com.aixingfu.sports.ui.fragment;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.aixingfu.sports.MVP.contract.CachaParamContract;
import com.aixingfu.sports.MVP.contract.DiscountContract;
import com.aixingfu.sports.MVP.contract.RenewContract;
import com.aixingfu.sports.MVP.contract.RenewType2Contract;
import com.aixingfu.sports.MVP.presenter.CacheParamPresenter;
import com.aixingfu.sports.MVP.presenter.DiscountPresenter;
import com.aixingfu.sports.MVP.presenter.RenewPresenter;
import com.aixingfu.sports.MVP.presenter.RenewType2Presenter;
import com.aixingfu.sports.Model.CacheParamModel;
import com.aixingfu.sports.Model.DiscountModel;
import com.aixingfu.sports.Model.RenewModel;
import com.aixingfu.sports.Model.RenewType2Model;
import com.aixingfu.sports.R;
import com.aixingfu.sports.ui.activity.RenewPaymentTimeActivity;
import com.aixingfu.sports.view.PopRenewCheckChooseID;
import com.aixingfu.sports.view.PopTimeCheckChooseID;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;
import com.orie.librarybase.utils.MoneyEditUtils;
import com.vondear.rxtool.RxTimeTool;
import com.vondear.rxtool.view.RxToast;

import org.json.JSONArray;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

import static android.content.Context.INPUT_METHOD_SERVICE;

/**
 * Created by 吕冬冬 on 2019.05.10.
 *
 * @auhtor 吕冬冬
 * email 863964634@qq.com
 * 内容: 续费Fragment
 * 修改人：
 * 修改时间：
 * 修改备注：
 */
public class IncreaseValidTimeFragment extends Fragment implements  DiscountContract.MyView, RenewType2Contract.MyView, CachaParamContract.MyView {
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    @BindView(R.id.tv_valid_time)
    TextView tvValidTime;
    @BindView(R.id.ll_valid_time)
    LinearLayout llValidTime;
    @BindView(R.id.ed_price)
    EditText edPrice;
    @BindView(R.id.tv_time)
    TextView tvTime;
    @BindView(R.id.ed_remarks)
    EditText edRemarks;
    @BindView(R.id.tv_back)
    TextView tvBack;
    @BindView(R.id.tv_next)
    TextView tvNext;
    Unbinder unbinder;

    private String mParam1;
    private String mParam2;
    private RenewType2Presenter renewType2Presenter;
    private String memberCardId, memberId;
    private String validTime,mprice,time,remarks;
    private PopTimeCheckChooseID popTimeCheckChooseID;
    private List<RenewType2Model.DataBeanX.ValidityRenewalBean> card_category_info;
    private String card_category_id="";
    private RenewPresenter renewPresenter;
    private CacheParamPresenter cacheParamPresenter;
    private String effective_time= "";
    private String invalid_time = "";
    private RenewType2Model.DataBeanX.ValidityRenewalBean validityRenewalBean;
    public IncreaseValidTimeFragment() {
    }

    public static IncreaseValidTimeFragment newInstance(String param1, String param2) {
        IncreaseValidTimeFragment fragment = new IncreaseValidTimeFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_increase_valid_time, container, false);
        unbinder = ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();
        initData();
    }


    private void initView() {
        Bundle bundle = getActivity().getIntent().getExtras();
        memberCardId = bundle.getString("memberCardId", "");
        memberId = bundle.getString("memberId", "");
        card_category_id = bundle.getString("card_category_id", "");
        invalid_time = bundle.getString("invalid_time", "");
        renewType2Presenter = new RenewType2Presenter();
        renewType2Presenter.attachView(this);
        cacheParamPresenter = new CacheParamPresenter();
        cacheParamPresenter.attachView(this);
        MoneyEditUtils.afterDotTwo(edPrice);
        getRenew();

    }

    private void initData() {
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick({R.id.ll_valid_time, R.id.tv_back, R.id.tv_next})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_valid_time:
                hideIputKeyboard();
                if (popTimeCheckChooseID != null){
                    popTimeCheckChooseID.showPop(tvValidTime);
                }

                break;
            case R.id.tv_back:
                hideIputKeyboard();
                getActivity().finish();
                break;
            case R.id.tv_next:
                validTime = tvValidTime.getText().toString();
                mprice = edPrice.getText().toString();
                time = tvTime.getText().toString();
                remarks = edRemarks.getText().toString();
                if (TextUtils.isEmpty(validTime)){
                    RxToast.normal(getActivity(),"请选择有效时间").show();
                }else if (TextUtils.isEmpty(mprice)){
                    RxToast.normal(getActivity(),"请输入价格").show();
                }else if (TextUtils.isEmpty(time)){
                    RxToast.normal(getActivity(),"请输入使用期限").show();
                }else {
                    getCacheParam();
                }
                break;
        }
    }
    public void getRenew() {
        if (renewType2Presenter.isViewAttached()) {
            HashMap<String, String> map = new HashMap<>();
            map.put("member_card_id", memberCardId);
            map.put("member_id", memberId);
            map.put("type", "2");
            renewType2Presenter.getRenewType2(map);
        }
    }

    public void getCacheParam() {
        if (cacheParamPresenter.isViewAttached()) {
            HashMap<String, String> map = new HashMap<>();
            map.put("card_category_id", card_category_id);
            map.put("member_id", memberId);
            map.put("old_member_card_id", memberCardId);
            map.put("renewal_way", "2");
            map.put("total_amount", mprice);
            map.put("note", remarks);
            map.put("effective_time", effective_time);
            map.put("renewal_price", mprice);
            map.put("android", "1");
            cacheParamPresenter.getCacheParam(map);
        }
    }
    @Override
    public void showToast(String msg, String state) {
    }

    @Override
    public void setFailed(String msg) {

    }

    @Override
    public void setCacheParam(CacheParamModel data) {
        if (data.getCode() == 1){
            ARouter.getInstance().build("/main/RenewPaymentTimeActivity").withString("member_id",memberId).navigation();
            RxToast.normal(getActivity(),data.getMessage()).show();
        }else {
            RxToast.normal(getActivity(),data.getMessage()).show();
        }
    }

    @Override
    public void setRenewType2(RenewType2Model data) {
                if (data.getCode() == 1){
                    try {
                        card_category_info = data.getData().getData().getValidity_renewal();
                        popTimeCheckChooseID = new PopTimeCheckChooseID(getActivity(), card_category_info);
                        popTimeCheckChooseID.setTagTxt("请选择")//设置顶部title的内容
                                .setButtomTxt("取消")//设置底部按钮内容
                                .setChoiceMode(AbsListView.CHOICE_MODE_SINGLE);//单选
                        //单选
                        popTimeCheckChooseID.setOnEventLisenter(positionList -> {
                            popTimeCheckChooseID.dismiss();
                            String type = card_category_info.get(positionList.get(0)).getType();
                            if ("y".equals(type)){
                                tvValidTime.setText(card_category_info.get(positionList.get(0)).getDay()+"年");
                                validityRenewalBean = card_category_info.get(positionList.get(0));
                                effective_time = JSON.toJSONString(validityRenewalBean);
                                int day = Integer.parseInt(card_category_info.get(positionList.get(0)).getDay());
                                int lastTime= Integer.parseInt(invalid_time)+day*365*24*60*60;
                                tvTime.setText(RxTimeTool.stampToDate(invalid_time)+ "到"+ RxTimeTool.stampToDate(String.valueOf(lastTime)));
                            }else if ("m".equals(type)){
                                tvValidTime.setText(card_category_info.get(positionList.get(0)).getDay()+ "月");
                                validityRenewalBean = card_category_info.get(positionList.get(0));
                                effective_time = JSON.toJSONString(validityRenewalBean);
                                int day = Integer.parseInt(card_category_info.get(positionList.get(0)).getDay());
                                int lastTime= Integer.parseInt(invalid_time)+day*30*24*60*60;
                                tvTime.setText(RxTimeTool.stampToDate(invalid_time)+ "到"+ RxTimeTool.stampToDate(String.valueOf(lastTime)));
//
                            }else if ("d".equals(type)){
                                tvValidTime.setText(card_category_info.get(positionList.get(0)).getDay()+ "天");
                                validityRenewalBean = card_category_info.get(positionList.get(0));
                                effective_time = JSON.toJSONString(validityRenewalBean);
                                int day = Integer.parseInt(card_category_info.get(positionList.get(0)).getDay());
                                int lastTime= Integer.parseInt(invalid_time)+day*24*60*60;
                                tvTime.setText(RxTimeTool.stampToDate(invalid_time)+ "到"+ RxTimeTool.stampToDate(String.valueOf(lastTime)));
                            }

                        });
                    }catch (Exception e){
                        e.printStackTrace();
                    }

        }
    }


    @Override
    public void setDiscount(DiscountModel data) {

    }


    @Override
    public void showLoading() {

    }
    @Override
    public void hideLoading() {

    }
    @Override
    public Context getMyContext() {
        return getActivity();
    }
    //关闭软键盘
    public void hideIputKeyboard() {
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                InputMethodManager mInputKeyBoard = (InputMethodManager) getActivity().getSystemService(INPUT_METHOD_SERVICE);
                if (getActivity().getCurrentFocus() != null) {
                    mInputKeyBoard.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(),
                            InputMethodManager.HIDE_NOT_ALWAYS);
                    getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
                }
            }
        });
    }
}
